package com.cedifie.analysis.http

import com.cedifie.analysis.AnalysisBuilder
import com.cedifie.analysis.aes.AnalysisAesUtil
import com.cedifie.http.OkHttp
import com.cedifie.http.callback.StringCallback
import com.cedifie.http.model.Response

object UrlHelper {

    fun combineUrl(): String {
        if (AnalysisBuilder.host.isBlank() or
            AnalysisBuilder.zone.isBlank() or
            AnalysisBuilder.pathCommon.isBlank()
        ) {
            return ""
        }

        val zone = AnalysisBuilder.zone
        AnalysisBuilder.zone = zone.replace("/", "")

        val pathCommon = AnalysisBuilder.pathCommon
        AnalysisBuilder.pathCommon = if (pathCommon.startsWith("/")) {
            pathCommon.replace("/", "")
        } else {
            pathCommon
        }

        return AnalysisBuilder.host + "/" + AnalysisBuilder.zone + "/" + AnalysisBuilder.pathCommon
    }
}

object HttpHelper {
    fun postData(toUrl: String, body: String) {
        if (toUrl.isBlank()) return
        if (body.isBlank()) return

        println(">>>>>analysis toUrl:$toUrl")
        println(">>>>>analysis body:$body")
        println(">>>>>analysis body aes:${AnalysisAesUtil.decryptDefault(body)}")
        OkHttp.post<String>(toUrl) // 请求方式和请求url
            .tag(this) // 请求的 tag, 主要用于取消对应的请求
            .upString(body)
            .execute(object : StringCallback() {
                override fun onSuccess(response: Response<String>) {
                    val respBody = response.body()
                    if (response.code() != 200 || respBody == null || respBody.isEmpty()){
                        println(">>>>>$toUrl>>>analysis errorCode： ${response.code()}, errorMsg: ${response.message()}")
                        return
                    }

                    val result = AnalysisAesUtil.decryptDefault(respBody)
                    if (result.isNotEmpty()){
                        println(">>>>>$toUrl>>>analysis success : $result")
                    }
                }

                override fun onError(response: Response<String>) {
                    println(">>>>>$toUrl>>>analysis errorCode： ${response.code()}, errorMsg: ${response.message()}")
                }
                override fun onFinish() {
                }
            })
    }
}


